// base
import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTEDITJOBINTENTION } from './store/actions/pageeditjobintention'
import { UPDATEPAGEEDITJOBINTENTION } from './store/types/pageeditjobintention'
import { UPDATEPAGECHOOSEJOBAREA } from '../choose-job-area/store/types/pagechoosejobarea'
// less
import './index.less'

// componnet
import { navigateTo, navigateBack } from '../../crossplatform/apiservice/navigate'
import pagejumplist from '../../configuration/pagejumplist.json'
import BtnFixedDelete from '../../components/page-components/btn-fixed-delete'
import { showToast } from '../../crossplatform/apiservice/toast/index'
import {
  addCareerObjectiveRequest,
  deljobHuntingRequest,
  editCareerObjectiveRequest
} from '../../service/user-archive-controller'
import Dialog from '../../components/page-components/dialog'
// libs

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGEEDITJOBINTENTION,
      payload: {
        ...payload
      }
    })
  },
  updateJobAreaState(payload) {
    dispatch({
      type: UPDATEPAGECHOOSEJOBAREA,
      payload: {
        ...payload
      }
    })
  },
  dorequest() {
    return new Promise(resolve => {
      let promise = DOREQUESTEDITJOBINTENTION()
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  }
})

@connect(
  ({ pagenewjobintention, landmark, userinfo, pageeditjobintention }) => ({
    userinfo,
    ...pageeditjobintention,
    landmarkName: landmark.landmarkName,
    archiveId: pagenewjobintention.archiveId,
    wantWork: pagenewjobintention.wantWork
  }),
  mapActiontoProps
)
class EditJobIntention extends Component {
  config = {
    navigationBarTitleText: '求职意向'
  }
  static defaultProps = {
    dataSource: []
  }

  constructor(props) {
    super(props)
    this.state = {
      modalVisible: false,
      preWorkNature: [],
      wantWorkId: '',
      workIndex: 0
    }
  }

  componentWillMount() {
    // onLoad
    const { wantWorkId, workIndex } = this.$router.params
    if (wantWorkId) {
      this.setState({
        wantWorkId,
        workIndex
      })
    }
  }

  componentDidMount() {
    // onready
    const { isEdit, workIndex } = this.$router && this.$router.params
    let {
      workPlace,
      workNature,
      workCategory,
      wantWork,
      landmarkName,
      jobCity,
      updateState
    } = this.props
    if (parseInt(isEdit) === 1) {
      let comprehensive = wantWork[workIndex] && JSON.parse(wantWork[workIndex].comprehensive)
      workNature = comprehensive.workNature
      workCategory = comprehensive.workCategory
      workPlace = comprehensive.workPlace
      jobCity = comprehensive.jobPlace || landmarkName
      this.setState({
        preWorkNature: [...workNature]
      })
      updateState({
        workNature,
        workCategory,
        workPlace,
        jobCity
      })
    }
    console.info('componentDidMount', isEdit)
  }

  getWorkPlaceFromWantWork = () => {
    let { wantWork } = this.props
    let workPlace = []
    if (wantWork[3] && wantWork[3].value) {
      workPlace = wantWork[3].value.split(' ')
      workPlace = workPlace.filter((item, index) => index > 0)
    }
    return workPlace
  }

  componentDidShow() {
    // onshow
    this.isChangeNature()
  }

  componentDidHide() {
    // onhide
  }

  componentWillUnmount() {
    // onUnload
    let { updateState } = this.props
    updateState({
      workPlace: [],
      workNature: [],
      workCategory: []
    })
    this.setState({
      preWorkNature: []
    })
  }

  checkIntentionRepeat = () => {
    const { wantWork, workNature } = this.props
    const { workIndex } = this.$router && this.$router.params
    let flag = false
    let wantWorkNew = []
    wantWork.map((item, index) => {
      index === parseInt(workIndex) ? null : wantWorkNew.push(item)
      return item
    })
    wantWorkNew.map(item => {
      const comprehensive = item.comprehensive ? JSON.parse(item.comprehensive) : {}
      const workNatureItem = comprehensive.workNature && comprehensive.workNature[0]
      if (workNatureItem == workNature[0]) {
        flag = true
      }
    })
    return flag
  }

  jumpToWorkNature = () => {
    const { workNature } = this.props
    this.setState({
      preWorkNature: [...workNature]
    })
    navigateTo({
      url: `${pagejumplist['choose-work-nature'].path}`
    })
  }

  jumpToJobArea = () => {
    const { workNature } = this.props
    this.setState({
      preWorkNature: [...workNature]
    })
    navigateTo({
      url: `${pagejumplist['choose-job-area'].path}`
    })
  }

  jumpToDesireJob = () => {
    const { workNature } = this.props
    this.setState({
      preWorkNature: [...workNature]
    })
    if (workNature.length <= 0) {
      this.showToastMessage('请先选择工作性质')
      return
    }
    let type = 0 // 0-兼职 1-全职 2-实习
    switch (workNature[0]) {
      case '兼职':
        type = 0
        break
      case '全职':
        type = 1
        break
      case '实习':
        type = 2
        break
      default:
        type = 0
        break
    }
    navigateTo({
      url: `${pagejumplist['choose-desire-job'].path}?type=${type}`
    })
  }

  onTap = () => {
    // 点击完成
    const { workPlace, workNature, workCategory } = this.props
    if (workNature.length <= 0) {
      this.showToastMessage('请选择工作性质')
      return
    }
    if (workPlace.length <= 0) {
      this.showToastMessage('请选择工作区域')
      return
    }
    if (workCategory.length <= 0) {
      this.showToastMessage('请选择期望职位')
      return
    }
    if(this.checkIntentionRepeat()) {
      this.showToastMessage('工作性质不能重复')
      return
    }
    this.addCareerObjective()
  }

  isChangeNature = () => {
    // 判断是否修改了工作性质 更改了则清空期望职位数据
    const { workNature } = this.props
    const { preWorkNature } = this.state
    if (preWorkNature[0] != workNature[0]) {
      this.props.updateState({
        workCategory: []
      })
    }
  }

  addCareerObjective = () => {
    const { archiveId, userinfo, workPlace, workNature, jobCity, workCategory } = this.props
    const { isEdit, wantWorkId } = this.$router && this.$router.params
    let comprehensive = JSON.stringify({
      workNature: Array.isArray(workNature[0]) ? workNature[0] : workNature,
      workPlace,
      workCategory
    })
    if (parseInt(isEdit) === 1) {
      editCareerObjectiveRequest({
        jobPlace: jobCity,
        comprehensive,
        id: wantWorkId,
        userId: userinfo.userId,
        archiveId,
        userName: userinfo.userInfoC.userName
      }).then(({ data }) => {
        const { status, message } = data
        if (status) {
          navigateBack()
        } else {
          this.showToastMessage(message || '更新失败')
        }
      })
    } else {
      addCareerObjectiveRequest({
        jobPlace: jobCity,
        comprehensive,
        userId: userinfo.userId,
        archiveId,
        userName: userinfo.userInfoC.userName,
        gmtCreate: new Date().getTime()
      }).then(({ data }) => {
        console.info(data)
        const { status, message } = data
        if (status) {
          navigateBack()
        } else {
          this.showToastMessage(message || '添加失败')
        }
      })
    }
  }
  showToastMessage = message => {
    showToast({
      title: message
    })
  }

  onDelete = () => {
    // 点击删除
    this.setState({
      modalVisible: true
    })
  }

  onDeleteOk = () => {
    this.setState(
      {
        modalVisible: false
      },
      () => {
        this.deleteJobIntention()
      }
    )
  }

  deleteJobIntention = () => {
    const { userinfo } = this.props
    const { wantWorkId } = this.state
    deljobHuntingRequest({
      id: wantWorkId,
      userId: userinfo.userId
    }).then(({ data }) => {
      console.info(data)
      const { status, message } = data
      if (status) {
        navigateBack()
      } else {
        this.showToastMessage(message || '删除失败')
      }
    })
  }
  onDeleteCancel = () => {
    this.setState({
      modalVisible: false
    })
  }

  render() {
    const { isEdit } = this.$router && this.$router.params
    const { workPlace, workNature, workCategory } = this.props
    const { modalVisible } = this.state
    return (
      <View className="EditJobIntention_id63975">
        <View className="top-title">
          <View className="title">
            <View className="title-text">{parseInt(isEdit) === 0 ? '新增' : '编辑'}求职意向</View>
            {/* <View className="title-btn" onClick={this.getSubmitData}>保存</View> */}
          </View>
          <View className="desc">*求职意向的不同，推荐的职位也会不同</View>
        </View>

        <View className="input-list">
          <View className="list-item" onClick={this.jumpToWorkNature}>
            <View className="item-title">工作性质</View>
            <View className="item-desc">
              <Text>{workNature.length > 0 ? workNature[0] : '请选择'}</Text>
              <Image
                className="item-arrow"
                src="https://imagesize.hrwork.com/sp/files/8db9c17d-2da7-4a9e-a44c-98a32670fcc7.png"
              />
            </View>
          </View>

          <View className="list-item" onClick={this.jumpToJobArea}>
            <View className="item-title">工作区域</View>
            <View className="item-desc">
              <Text>{workPlace.length > 0 ? workPlace.join(' ') : '请选择'}</Text>
              <Image
                className="item-arrow"
                src="https://imagesize.hrwork.com/sp/files/8db9c17d-2da7-4a9e-a44c-98a32670fcc7.png"
              />
            </View>
          </View>

          <View className="list-item" onClick={this.jumpToDesireJob}>
            <View className="item-title">期望职位</View>
            <View className="item-desc">
              <Text>{workCategory.length > 0 ? workCategory.join(' ') : '请选择'}</Text>
              <Image
                className="item-arrow"
                src="https://imagesize.hrwork.com/sp/files/8db9c17d-2da7-4a9e-a44c-98a32670fcc7.png"
              />
            </View>
          </View>
        </View>
        <BtnFixedDelete
          // leftText={`${isEdit == 0 ? '' : '删除本条'}`}
          leftText=""
          rightText="完成"
          onDelete={this.onDelete}
          onTap={this.onTap}
        />
        <AtActionSheet isOpened={modalVisible}>
          <Dialog
            title="温馨提示"
            subtext="您确定删除这条求职意向吗？"
            leftText="取消"
            rightText="确认"
            onOk={this.onDeleteOk}
            onLeftOk={this.onDeleteCancel}
          />
        </AtActionSheet>
      </View>
    )
  }
}

EditJobIntention.defaultProps = {
  workArea: {
    choosedCityList: []
  }
}
export default EditJobIntention
